package com.epc.easypurchase.fragment

import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import com.epc.easypurchase.R
import com.epc.easypurchase.activity.MainActivity
import com.epc.easypurchase.constant.SPUserConstants
import com.epc.easypurchase.mvp.contract.LogoutContract
import com.epc.easypurchase.mvp.presenter.LogoutPresenter
import com.epc.easypurchase.util.SPUserUtil
import com.epc.easypurchase.util.SimpleDialogUtil
import com.woochen.baselibrary.base.mvp.BaseMvpFragment
import com.woochen.baselibrary.mvp.InjectPresenter
import kotlinx.android.synthetic.main.frament_main.*

/**
 * Created by chenwuchao on 2018/11/24.
 */
class HomeFragment : BaseMvpFragment(), LogoutContract.ILogoutView, View.OnClickListener {


    @InjectPresenter
    lateinit var mLogoutPresenter: LogoutPresenter

    override fun logoutSucess() {
        startActivity(MainActivity::class.java)
    }

    override fun setContentView(): Int = R.layout.frament_main

    companion object {
        private val URL_NAME: String = "url_name"

        fun newInstance(url: String): HomeFragment {
            val homeFragment = HomeFragment()
            val arguments = Bundle()
            arguments.putString(URL_NAME, url)
            homeFragment.arguments = arguments
            return homeFragment
        }
    }

    override fun initView() {
        initListener()
        showLoading(false)
        initWebView()
        var url = this.arguments.getString(URL_NAME)
        val headParams = hashMapOf<String, String>()
        val token = SPUserUtil.getString(SPUserConstants.USER_TOKEN)!!
        headParams.put("epc-token", token)
        url = url + "?epc-token=" + token
        web.loadUrl(url, headParams)
    }

    private fun initListener() {
        iv_back.setOnClickListener(this)
    }

    private fun initWebView() {
        web.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                showContent()
            }

            override fun onLoadResource(view: WebView?, url: String?) {
                println("->" + url + " token ->" + SPUserUtil.getString(SPUserConstants.USER_TOKEN))
            }
        }
        web.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                tv_title.text = title
            }
        }
        val webSettings = web.settings
        webSettings.javaScriptEnabled = true
        web.addJavascriptInterface(this, "android")
        // 支持缩放(适配到当前屏幕)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {//少于4.4（不包括4.4）用这个
            webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        }
        //适应屏幕，大于等于4.4用这个
        webSettings.useWideViewPort = true
        webSettings.setSupportZoom(true)
        webSettings.loadWithOverviewMode = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不缓存
        web.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK ) {
                isCanGoBack()
            }else false
        }

    }

    fun isCanGoBack():Boolean{
        if (web.canGoBack()) {
            web.goBack()
          return  true
        } else  return false
    }

    @JavascriptInterface
    fun logout() {
        SimpleDialogUtil.confirmAndCancel(mContext, R.string.tip_logout, R.string.cancle, R.string.confirm,
                object : SimpleDialogUtil.SimpleClickListener {
                    override fun confirm() {
                        mLogoutPresenter.logout()
                    }

                })
    }


    override fun onClick(v: View?) {
        when (v) {
            iv_back -> {
                isCanGoBack()
            }

        }
    }
}